var _util = require('../../util/util.js')
const _main_service = require('../../service/main_service.js')
const _cart_service = require('../../service/cart_service.js')
require('./index.css')

// 获取存储在 localStorage 中的用户信息
const userInfo = localStorage.getItem('userInfo');
const user = JSON.parse(userInfo);

//我的订单的跳转
$('#myorder').on('click', function () {
    window.location.href = '../../view/myOrder.html'
})

//购物车结算
$('a.btn.btn-primary.btn-cart').on('click', function () {
    localStorage.setItem('fromCart', 1);
})


const user_main = {
    init: function () {

        if (userInfo) {
            this.checkLoginAndLoadCart(user);  // 检查用户登录状态并加载购物车
        } else {
            console.log("没有找到用户信息，用户未登录");
        }

        $(".thumbImg").mouseenter(function (event) {
            console.log("鼠标移入图片");

            // 获取商品的相关数据
            let productName = $(this).data('name');
            let productPrice = $(this).data('price');
            let productDescription = $(this).data('description');

            // 设置悬浮窗的内容
            $("#hover-product-name").text(productName);
            $("#hover-product-price").text(productPrice);
            $("#hover-product-description").text(productDescription);

            // 获取图片的位置（相对于页面的坐标）
            let imgOffset = $(this).offset();  // 获取图片的偏移位置
            let imgWidth = $(this).width();     // 获取图片的宽度
            let imgHeight = $(this).height();   // 获取图片的高度

            // 计算悬浮窗的位置，放在图片的正上方
            let mouseX = imgOffset.left + imgWidth / 2 - $("#product-hover-info").width() / 2;  // 居中显示
            let mouseY = imgOffset.top - $("#product-hover-info").height() - 10;  // 放在图片的上方，距离图片10px

            // 显示悬浮窗并调整位置
            $("#product-hover-info").css({
                "left": mouseX + "px",
                "top": mouseY + "px",
                "display": "block"
            });

        });

        $(".thumbImg").mouseleave(function () {
            console.log("鼠标移出图片");
            $("#product-hover-info").hide();
        });

        this.bindEvent();
        return this;
    },

    bindEvent: function () {
        const _this = this;

        // 页面初始化后加载首页数据
        _main_service.getHomepageData(function (data) {
            _this.renderProductList(data.productList);  // 渲染商品列表
            _this.renderHeader(data); // 渲染头部
        }, function (errMsg) {
            _util.errorTips('首页加载失败：' + errMsg);  // 错误提示
        });

        // 监听搜索事件
        $('#searchButton').click(function () {
            _this.searchItem();
        });
    },

    // 检查用户登录状态并加载购物车
    async checkLoginAndLoadCart(user) {
        try {
            await this.renderUserInfo(user);
            if (user) {
                await this.loadCartData();
            } else {
                $('#topBarItemCount').text('（0）');
            }
        } catch (err) {
            console.error('获取用户登录信息失败:', err);
            $('#topBarItemCount').text('（0）');
        }
    },

    // 获取用户信息并渲染
    async renderUserInfo(user) {
        try {
            if (user && user.username) {
                $("#loggedInSection").show();
                $("#notLoggedInSection").hide();

                $("#welcomeUser").text(`欢迎回来！${user.username}`);
                $("#username").val(user.username || "");
                $("#email").val(user.email || "");
                $("#age").val(user.age || "");
            } else {
                $("#loggedInSection").hide();
                $("#notLoggedInSection").show();
            }

            return user;
        } catch (error) {
            console.error("获取用户信息失败：", error);
            $("#loggedInSection").hide();
            $("#notLoggedInSection").show();

            return null;
        }
    },

    // 加载购物车数据
    async loadCartData() {
        _cart_service.getCartData(
            user.id,
            function (cart) {
                console.log(cart.itemList);
                // === 成功回调 ===
                const $cartContainer = $('#cartContainer');
                const $list = $('#J_miniCartList');
                const $totalCount = $('#CartListTotalCount');
                const $totalPrice = $('#CartListTotalPrice');
                const $itemCount = $('#topBarItemCount');
                const $emptyCart = $('#emptyCart');

                $list.empty();

                if (cart && cart.totalCount > 0) {
                    $cartContainer.show();
                    $emptyCart.hide();

                    cart.itemList.forEach(item => {
                        const $li = $(`
                          <li class="cart-item" data-item-id="${item.itemID}">
                            <div class="clearfix first">
                              <a class="thumb">
                                <img alt="${item.name}" src="${item.url}">
                              </a>
                              <span id="ItemName" class="name">${item.name}</span>
                              <span class="price Item-price">${item.price}</span>
                              <div class="count-control">
                                <button class="count_d">-</button>
                                <span class="price Item-count">${item.itemNum}</span>
                                <button class="count_i">+</button>
                              </div>
                              <a class="btn-del J_delItem">
                                <em class="iconfont-close"></em>
                              </a>
                            </div>
                          </li>
                        `);
                        $list.append($li);
                    });

                    $totalCount.text(cart.totalCount);
                    $totalPrice.text(cart.totalPrice);
                    $itemCount.text(`（${cart.totalCount}）`);

                    let cartList = document.getElementById("J_miniCartList");
                    if (cartList) {
                        let cartItems = cartList.children;
                        console.log(cartItems);
                        let currentCartListTotalCount = parseInt($('#CartListTotalCount').text());
                        let currentCartListTotalPrice = parseInt($('#CartListTotalPrice').text());
                        if (cartItems && cartItems.length > 0) {
                            for (let cartItem of cartItems) {
                                console.log(cartItem);
                                let i_btn = cartItem.querySelector(".count_i");
                                let d_btn = cartItem.querySelector(".count_d");
                                let itemCount = cartItem.querySelector(".Item-count");
                                let itemPrice = cartItem.querySelector(".Item-price");
                                let currentCount = parseInt(itemCount.textContent);
                                let ItemPrice = parseInt(itemPrice.textContent);
                                let itemId = cartItem.getAttribute('data-item-id');
                                let delBtn = cartItem.querySelector('.btn-del');
                                // **删除商品**
                                delBtn.addEventListener("click", async (event) => {
                                    let result = confirm("确定删除吗?");
                                    if (!result) return;
                                    _cart_service.removeItem(
                                        user.id,
                                        itemId,
                                        function () {
                                            console.log("删除成功");
                                            alert("删除成功");

                                            currentCartListTotalCount -= currentCount;
                                            currentCartListTotalPrice -= ItemPrice * currentCount;

                                            $('#topBarItemCount').text(`(${currentCartListTotalCount})`);

                                            if (currentCartListTotalCount > 0) {
                                                cartList.removeChild(event.target.closest('li'));
                                                $('#CartListTotalCount').text(currentCartListTotalCount);
                                                $('#CartListTotalPrice').text(currentCartListTotalPrice);
                                            } else {
                                                $('#J_miniCartList').html('');
                                                $('#J_miniCartListTotal').html('<div class="msg msg-empty">购物车中还没有商品，赶紧选购吧！</div>');
                                            }
                                        },
                                        function (error) {
                                            console.error("删除失败", error);
                                            alert("删除失败");
                                        }
                                    );
                                });
                                // **增加商品数量**
                                i_btn.addEventListener("click", () => {
                                    console.log("+1")
                                    currentCount++;
                                    currentCartListTotalCount++;
                                    currentCartListTotalPrice += ItemPrice;
                                    itemCount.textContent = String(currentCount);
                                    $('#CartListTotalCount').text(currentCartListTotalCount);
                                    $('#CartListTotalPrice').text(currentCartListTotalPrice);
                                    $('#topBarItemCount').text(`(${currentCartListTotalCount})`);
                                    updateDatabase(itemId, currentCount);
                                });
                                // **减少商品数量**
                                d_btn.addEventListener("click", async (event) => {
                                    console.log("-1")
                                    currentCount--;
                                    currentCartListTotalCount--;
                                    currentCartListTotalPrice -= ItemPrice;
                                    if (currentCount === 0) {
                                        let result = confirm("本次操作将从购物车移除此商品，确定删除吗?");
                                        if (!result) {
                                            currentCount++;
                                            currentCartListTotalCount++;
                                            currentCartListTotalPrice += ItemPrice;
                                            return;
                                        }
                                        $('#topBarItemCount').text(`(${currentCartListTotalCount})`);
                                        _cart_service.removeItem(
                                            user.id,
                                            itemId,
                                            function () {
                                                console.log("删除成功");
                                                cartList.removeChild(event.target.closest('li'));
                                                $('#CartListTotalCount').text(currentCartListTotalCount);
                                                $('#CartListTotalPrice').text(currentCartListTotalPrice);

                                                if (currentCartListTotalCount === 0) {
                                                    $('#J_miniCartList').html('');
                                                    $('#J_miniCartListTotal').html('<div class="msg msg-empty">购物车中还没有商品，赶紧选购吧！</div>');
                                                }
                                            },
                                            function (error) {
                                                console.error("删除失败", error);
                                                alert("删除失败");

                                                currentCount++;
                                                currentCartListTotalCount++;
                                                currentCartListTotalPrice += ItemPrice;
                                            }
                                        );
                                    } else {
                                        itemCount.textContent = String(currentCount);
                                        $('#CartListTotalCount').text(currentCartListTotalCount);
                                        $('#CartListTotalPrice').text(currentCartListTotalPrice);
                                        $('#topBarItemCount').text(`(${currentCartListTotalCount})`);
                                        updateDatabase(user.id, itemId, currentCount);
                                    }
                                });
                            }
                        }
                    }
                } else {
                    $cartContainer.show();
                    $emptyCart.show();
                    $itemCount.text('（0）');
                }
            },
            function (err) {
                // === 失败回调 ===
                console.error('加载购物车失败:', err);
            }
        );
    },

    // 搜索商品
    searchItem: function () {
        var query = $('#search').val().trim();
        if (query.length < 1) {
            $('#J_keywordList').hide();
            return;
        }

        _util.fetch("/search", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ key: query })
        })
            .then(response => response.json())
            .then(results => {
                this.displaySearchResults(results);
            })
            .catch(error => {
                console.error("搜索请求出错：", error);
            });
    },

    // 显示搜索结果
    displaySearchResults: function (results) {
        const resultsContainer = $('#J_keywordList');
        const resultList = resultsContainer.find('.result-list');
        resultList.empty();

        if (results.length > 0) {
            resultsContainer.show();
            results.forEach(function (item) {
                const li = $('<li>');
                const a = $('<a>', {
                    text: item.name,
                    href: "javascript:void(0);", // 防止跳转
                    click: function () { goToCart(this); }, // 绑定点击事件
                    'data-id': item.id,
                    'data-name': item.name,
                    'data-price': item.price,
                    'data-description': item.description,
                    'data-url': item.url
                });
                li.append(a);
                resultList.append(li);
            });
        } else {
            resultsContainer.hide();
            resultList.append('<li>没有找到相关商品</li>');
        }
    },

    // 渲染商品列表
    renderProductList: function (productList) {
        var template = `
            {{#productList}}
            <div class="home-brick-box home-brick-row-2-box xm-plain-box" id="{{description}}">
                <div class="box-hd">
                    <h2 class="title" style="font-weight: bolder">{{description}}</h2>
                </div>
                <div class="box-hd clearfix" style="height: 686px">
                    <div class="row" style="margin-left: -14px">
                        <div class="span4">
                            <ul class="brick-promo-list clearfix">
                                <li class="brick-item brick-item-l">
                                    <a href=""></a>
                                </li>
                            </ul>
                        </div>
                        <div class="span16">
                            <ul class="brick-list clearfix">
                                {{#items}}
                                <li class="brick-item brick-item-m brick-item-m-2">
                                    <a href="javascript:void(0);" onclick="goToCart(this)" data-item='{{&.}}'>
                                        <div class="figure figure-img">
                                            <img class="thumbImg" width="160" height="160" alt="{{name}}" src="{{url}}" data-name="{{name}}" data-price="{{price}}" data-description="{{description}}" data-id="{{id}}">
                                        </div>
                                        <h3 class="title">{{name}}</h3>
                                        <p class="price">
                                            <span class="num">{{price}}</span>元<span>起</span>
                                            <del><span class="num">1000</span>元</del>
                                        </p>
                                    </a>
                                </li>
                                {{/items}}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            {{/productList}}
        `;

        var html = _util.renderHTML(template, { productList: productList });
        $('#product-container').html(html);
    },

    renderHeader: function (data) {
        const headerTemplate = $('#header-template').html();
        const html = _util.renderHTML(headerTemplate, {
            productList: data.productList,
            categoryList: data.categoryList
        });
        $('.header-nav .nav-list').html(html);
    }
};

goToCart = function (el) {
    // 获取当前 item 的父元素
    const $img = $(el).find("img.thumbImg");
    if ($img.length === 0) return;

    const item = {
        id: $img.data("id") || '',
        name: $img.data("name") || '',
        price: $img.data("price") || '',
        description: $img.data("description") || '',
        url: $img.attr("src") || ''
    };

    localStorage.setItem("selectedItem", JSON.stringify(item));
    window.location.href = "/view/ShoppingCart.html";
};

goToCartBySearch = function (el) {
    const $a = $(el);
    const item = {
        id: $a.data("id") || '',
        name: $a.data("name") || '',
        price: $a.data("price") || '',
        description: $a.data("description") || '',
        url: $a.data("url") || ''
    };

    localStorage.setItem("selectedItem", JSON.stringify(item));
    window.location.href = "/view/ShoppingCart.html";
};

// 页面加载后初始化首页
$(function () {
    user_main.init();
})

$('.link').on('mouseenter', function () {
    // 显示购物车弹出层
    $('#J_miniCartMenu').css('height', 'auto');

    // 加载购物车数据
    user_main.loadCartData();
});

$('#cartContainer').on('mouseleave', function () {
    $('#J_miniCartMenu').css('height', '0');
});

const updateDatabase = (itemID, count) => {
    _cart_service.updateCart(user.id, itemID, count,
        function (res) {
            console.log("数量更新成功", res);
        },
        function (err) {
            console.error("数量更新失败", err);
        }
    );
};